package org.meetunexpectedly.service.audit;

import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.util.StringMap;
import org.meetunexpectedly.config.QiNiuConfig;
import org.meetunexpectedly.constant.AuditStatus;
import org.meetunexpectedly.entity.json.*;
import org.meetunexpectedly.entity.response.AuditResponse;
import org.meetunexpectedly.entity.setting.Setting;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 图片审核服务
 * @Author: pupil
 * @Date: 2024/08/20 下午 4:05
 */
@Service
public class ImageAuditService extends AbstractAuditService<String, AuditResponse> {

    // 七牛云图片审核api
    private final static String imageUrl = "http://ai.qiniuapi.com/v1/image/censor";
    // 图片审核请求体模板
    private static String imageBody = "${url}\n" +
            "    \"data\": {\n" +
            "        \"uri\": \"$\"\n" +
            "    },\n" +
            "    \"params\": {\n" +
            "        \"scenes\": [\n" +
            "            \"pulp\",\n" +
            "            \"terror\",\n" +
            "            \"politician\"\n" +
            "        ]\n" +
            "    }\n" +
            "}";


    @Override
    public AuditResponse audit(String url) {
        AuditResponse auditResponse = new AuditResponse();
        auditResponse.setAuditStatus(AuditStatus.SUCCESS.num);

        // 判断是否开启审核
        if (!isNeedAudit()) {
            // 没有开启直接返回
            return auditResponse;
        }

        try {
            if (!url.contains(QiNiuConfig.RealmName)) {
                String encodedFileName = URLEncoder.encode(url, "utf-8").replace("+", "%20");
                url = String.format("%s/%s", QiNiuConfig.RealmName, encodedFileName);
            }

            url = appendUUID(url);

            String body = imageBody.replace("${url}", url);
            String method = "POST";
            String token = qiNiuConfig.getAuditToken(imageUrl, method, body, contentType);
            StringMap headers = new StringMap();
            headers.put("Host", "ai.qiniuapi.com");
            headers.put("Content-Type", contentType);
            headers.put("Authorization", token);


            // 创建配置并设置文件存储的服务区域
            Configuration cfg = new Configuration(qiNiuConfig.getRegion());
            Client client = new Client(cfg);

            Response response = client.post(imageUrl, body.getBytes(), headers, contentType);

            Map map = objectMapper.readValue(response.getInfo().split("\n")[2], Map.class);
            ResultChildJson resultChildJson = objectMapper.convertValue(map.get("result"), ResultChildJson.class);
            // 封装成bodyJson用于审核
            BodyJson bodyJson = new BodyJson();
            ResultJson resultJson = new ResultJson();
            resultJson.setResult(resultChildJson);
            bodyJson.setResult(resultJson);

            Setting setting = settingService.getById(settingId);
            SettingScoreJson settingScoreRule = objectMapper.readValue(setting.getAuditPolicy(), SettingScoreJson.class);
            List<ScoreJson> scoreJsonList = Arrays.asList(settingScoreRule.getSuccessScore(), settingScoreRule.getManualScore(), settingScoreRule.getPassScore());

            // 进行系统审核
            auditResponse = audit(scoreJsonList, bodyJson);
            return auditResponse;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return auditResponse;
    }
}
